<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>设置</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>

      <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">角色管理</h3>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input  placeholder="请输入角色姓名" clearable v-model="Rolename" @clear="searchRole">
            <el-button slot="append" icon="el-icon-search" @click="searchRole"></el-button>
          </el-input>
        </el-col>
      </el-row>
    </el-card>



    <el-card style="margin-top: 30px">
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="primary" size="mini" @click="showAddRoleDialog">+ 添加</el-button>
        </el-col>
      </el-row>


      <el-table :data="RoleList" border stripe>
        <el-table-column type="index"></el-table-column>

        <el-table-column label="角色名称" prop="rolename"></el-table-column>
        <el-table-column label="角色描述" prop="roledescription"></el-table-column>
        <el-table-column label="角色权限" prop=" "></el-table-column>

        <el-table-column label="添加人" prop="rolecode"></el-table-column>
        <el-table-column label="添加时间" prop="inserttime"></el-table-column>


        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="showRoleeditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button type="success" size="mini" @click="setRoleById(scope.row)">授权</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10 , 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>


    <div>
      <!--添加菜单-->
      <el-dialog title="添加角色" :visible.sync="addRoleFormVisible" @close="closeAddDialog">
        <el-form
            :model="addRoleForm"
            :rules="addRoleFormRules"
            ref="addRoleFormRef"
            label-width="200px"
            label-position="right"
            size="small"
            class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="rolename">
            <el-row :gutter="20">
              <el-col :span="20">
                <el-input v-model="addRoleForm.rolename"></el-input>
              </el-col>
            </el-row>
          </el-form-item>


          <el-form-item label="角色描述" prop="roledescription">
            <el-row :gutter="20">
              <el-col :span="20">
                <el-input v-model="addRoleForm.roledescription"></el-input>
              </el-col>
            </el-row>
          </el-form-item>


        </el-form>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-button type="primary" @click="addRole">确 认</el-button>
            <el-button @click="closeAddDialog">取 消</el-button>
          </el-col>
        </el-row>

      </el-dialog>
    </div>


    <div>
      <!--修改菜单-->
      <el-dialog title="修改员工" :visible.sync="editRoleFormVisible" @close="closeeditDialog">
        <el-form
            :model="editRoleForm"
            :rules="editRoleFormRules"
            ref="editRoleFormRef"
            label-width="200px"
            label-position="right"
            size="small"
            class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="rolename">
            <el-row :gutter="20">
              <el-col :span="20">
                <el-input v-model="editRoleForm.rolename"></el-input>
              </el-col>
            </el-row>
          </el-form-item>


          <el-form-item label="角色描述" prop="roledescription">
            <el-row :gutter="20">
              <el-col :span="20">
                <el-input v-model="editRoleForm.roledescription"></el-input>
              </el-col>
            </el-row>
          </el-form-item>



        </el-form>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-button type="primary" @click="editRole">确 认</el-button>
            <el-button @click="closeeditDialog">取 消</el-button>
          </el-col>
        </el-row>

      </el-dialog>
    </div>
<!--    授权-->
    <div>
      <el-dialog
          title="菜单权限"
          :visible.sync="authorityDialogVisible"
          width="50%"
          :close-on-click-modal="false"
          @close="cancelAuthorityMenu"
      >
        <el-form
            :model="authorityForm"
            :rules="authorityFormRules"
            ref="authorityFormRef"
            label-width="100px"
            class="demo-ruleForm"
        >
          <el-form-item label="角色ID" prop="roleId">
            <el-input v-model="authorityForm.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">

            <el-input v-model="authorityForm.rolename" disabled></el-input>
          </el-form-item>
          <!--:checkStrictly="true"-->
          <el-form-item label="菜单权限" prop="roleMenu">
            <el-tree
                :data="menuList"
                show-checkbox
                default-expand-all
                node-key="id"
                ref="roleMenuTree"
                highlight-current
                :props="defaultProps"
                :defaultCheckedKeys="defaultChekcedMenu"
                :check-strictly="true"
            ></el-tree>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="editAuthorityMenu">确 定</el-button>
                <el-button @click="cancelAuthorityMenu">取 消</el-button>
            </span>
      </el-dialog>

    </div>

  </div>
</template>
<script>
export default {
  data() {
    return {
      Rolename: "",
      pageNum: 1,
      pageSize: 5,
      total: 9,
      RoleList: [],
      addRoleFormVisible:false,
      addRoleForm:{
        rolecode: "",
        rolename: "",
        roledescription: "",
        inserttime: "",
        updatetime: "",
      },
      addRoleFormRules: {
        rolename: [
          {required: true, message: "請輸入姓名", trigger: "blur"},
          {min: 2, max: 16, message: "姓名必须是2-16个字符", trigger: "blur"}
        ]
      },
      editRoleFormVisible:false,
      editRoleForm:{
        rolecode: "",
        rolename: "",
        roledescription: "",
        inserttime: "",
        updatetime: "",
      },
      editRoleFormRules: {
        rolename: [
          {required: true, message: "請輸入姓名", trigger: "blur"},
          {min: 2, max: 16, message: "姓名必须是2-16个字符", trigger: "blur"}
        ]
      },

      authorityDialogVisible:false,
      authorityForm:{
        id:'',
        rolename:'',
        checkedIds:[]
      },
      authorityFormRules:{},
      menuList:[],
      defaultProps:{
        children:'children',
        label:'name'
      },
      defaultChekcedMenu:[],
    };
  },
  methods: {
    /*打开授权窗口*/
    setRoleById(row){
      this.authorityDialogVisible = true;


      this.authorityForm.id=row.id;
      this.authorityForm.rolename=row.rolename;

      let url = "role/getCheckedPer/"+row.id;
      this.$axios.get(url).then(res=>{
        if (res.data.code == 200){
          this.defaultChekcedMenu = res.data.data;
        }else{
          this.$message({
            type: "error",
            message: res.data.msg,
            duration: 1000
          })
        }
      })

    },
    /*关闭授权窗口*/
    cancelAuthorityMenu(){
      this.authorityDialogVisible =false;
      this.$refs.roleMenuTree.setCheckedKeys([]);
    },
    /*提交授权*/
    editAuthorityMenu(){
      let tree =this.$refs.roleMenuTree;
      let arrIds = tree.getCheckedKeys();

      this.authorityForm.checkedIds=arrIds;
      if(arrIds.length<1){
        this.$message({
          type:'error',
          message:'请至少选择一个权限',
          duration:1000
        })
        return;
      }
      let url = "role/rolePer";
      this.$axios.post(url,this.authorityForm).then(res=>{
        if(res.data.code==200){
          this.$message({
            type:'success',
            message:res.data.msg,
            duration:1000
          })
          this.authorityDialogVisible = false;
        }else {
          this.$message({
            type:'error',
            message:res.data.msg,
            duration:1000
          })
        }
      })

    },





    //删除Role
    removeRoleById(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url ="role/del/"+id;
        this.$axios.delete(url).then(res => {
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000
            })
            this.reloadData();
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
              duration: 1000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },




    //显示编辑窗口
    showRoleeditDialog(row) {
      this.editRoleFormVisible = true;
      this.editRoleForm = row;
    },
    //关闭编辑窗口
    closeeditDialog(){
      this.editRoleFormVisible = false;
      this.$refs.editRoleFormRef.resetFields();
      this.reloadData();
    },

    //编辑Role
    editRole() {
      this.$refs.editRoleFormRef.validate(valid => {
        if (!valid) {
          return;
        }
        let url = "role/edit"
        this.$axios.put(url, this.editRoleForm).then(res => {
          if (res.data.code = 200) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000
            })
            this.editRoleFormVisible = false;
            this.reloadData();

          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
              duration: 1000
            })
          }
        })
      })
    },



    //显示添加模态框
    showAddRoleDialog(){
      this.addRoleFormVisible=true;
    },
    //关闭添加模态框
    closeAddDialog(){
      this.addRoleFormVisible=false;
      this.$refs.addRoleFormRef.resetFields();
      this.reloadData();
    },

    //添加
    addRole() {
      this.$refs.addRoleFormRef.validate(valid => {
        if (!valid) {
          return;
        }

        let userjs =sessionStorage.getItem('userInfo');
        let user=JSON.parse(userjs);
        this.addRoleForm.rolecode=user.empaccount;


        let url = "role/add"
        this.$axios.post(url, this.addRoleForm).then(res => {
          if (res.data.code = 200) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000
            })
            this.addRoleFormVisible = false;
            this.reloadData();
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
              duration: 1000
            })
          }
        })
      })
    },



    //根据名字查所有Role
    getRoleList() {
      let url = "role/pageRolelist";
      this.$axios.get(url, {
        params: {
          name: this.Rolename,
          now: this.pageNum,
          size: this.pageSize
        }
      }).then(res => {
        if (res.data.code == 200) {
          this.RoleList = res.data.data.list;
          this.pageNum = res.data.data.pageNum;
          this.pageSize = res.data.data.pageSize;
          this.total = res.data.data.total;
        } else {
          this.$message({
            type: "error",
            message: res.data.msg,
            duration: 1000
          })
        }
      });
    },
    loadMenus() {
      let url ="menu/showMenusList"
      this.$axios.get(url).then(res=>{
        if(res.data.code == 200){
          this.menuList =res.data.data;
        }else{
          this.$message({
            type:'error',
            message:res.data.msg,
            duration:1000
          })
        }
      })
    },
    searchRole() {
      this.pageNum = 1;
      this.getRoleList();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getRoleList();
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.getRoleList();
    },
    //把用户对象中包含的roleList其中的rolename转换为逗号分隔的字符串
    getPerNames(arr) {
      if (!arr) return;
      let PerNameArr = new Array();
      for (let i = 0; i < arr.length; i++) {
        PerNameArr.push(arr[i].name);
      }
      return PerNameArr.join(",");
    },

    reloadData() {
      this.searchRole();

    }
  },
  created() {
    this.reloadData();
    this.loadMenus();
  }
};
</script>
<style lang="less" scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avata {
  width: 178px;
  height: 178px;
  display: block;
}
</style>